<template>
  <view class="mh-ql-wrapper">
    <view class="mh-ql-err-tip" v-if="errTipTxt&&(currentIndex>finishNum)&&currentIndex!=0">
      <view class="mh-ql-err-tip-ic"></view>
      <view class="mh-ql-err-tip-txt">{{ errTipTxt }}</view>
      <view class="mh-ql-err-tip-btn" @click="setErrTip('')"></view>
    </view>
    <view class="mh-ql-title">{{ mhqlTitle }}</view>
    <view
      class="mh-ql-group"
      v-for="(itemsObj, idx) in problemList"
      :key="idx"
      v-show="currentIndex === idx"
    >
      <view class="mh-ql-question">{{ idx + 1 }}.{{ itemsObj.question }}</view>
      <view class="mh-ql-answer-list">
        <view
          class="mh-ql-answer-item"
          :class="{'mh-ql-answer-item-active':itemsObj.answer === opts.opt}"
          v-for="(opts, oIdx) in itemsObj.opts"
          :key="oIdx"
          @click="seledMs(idx, opts)"
        >
          <view class="mh-ql-answer-txt">{{ opts.opt }}.{{ opts.txt }}</view>
          <view
            class="mh-ql-answer-status selected"
            v-if="itemsObj.answer === opts.opt"
          ></view>
          <view class="mh-ql-answer-status" v-else></view>
        </view>
      </view>
    </view>
    <view class="mh-ql-count" style="display:none"
      >已做题目数{{ finishNum }}/{{ problemList.length }}</view
    >



    <view class="mh-ql-btn-wrapper">
      <!-- <view
        class="mh-ql-btn mh-ql-btn-prev"
        v-if="currentIndex > 0"
        @click="goPrevMs"
        >上一题</view
      > -->
      <button v-if="currentIndex==0" :disabled="currentIndex==0">上一题</button>
      <button v-else  class="btn-active" @click="goPrevMs" >上一题</button>
      <button v-if="finishNum!=problemList.length" :disabled="finishNum!=problemList.length" >确认修改</button>
      <button v-else class="btn-active" @click="modifyConfirm"  >确认修改</button>
    </view> 
    <view class="tongji">
      <view class="tj-head" >
        <view  class="th-item">
          <view class="tj-box"></view>
          <text >已做{{finishNum}}题</text>
        </view>
        <view class="th-item th-item-unwrite">
          <view class="tj-box"></view>
          <text >未做{{problemList.length-finishNum}}题</text>
        </view>
      </view>
      <view class="tj-body" >
        <view class="tj-order" :class="{'item-select':item.answer!=''}" v-for="(item, k) in problemList" 
             @tap="orderClick(k)"
            :key="item.order">{{k+1}}</view>
      </view>
    </view>

  </view>
</template>

<script>
import { problemList } from "@/packageIsolate/pages/mentalHealth/questionList";
import { mentalHealth, getData } from "@/api";
import {getNowTime} from '@/utils'
export default {
  data() {
    return {
      mhqlTitle: "心理评估-失眠严重指数（ISI）",
      currentIndex: 0,
      finishNum: 0,
      problemList: [],
      ck: true,
      errTipTxt: '部分题目未填写',
      type: '',
      dataIsiArr: [],
      dataPhq9Arr: [],
      dataGad7Arr: [],
      reportType:{
        isolateUser: 0,
        systemUser:1,
      },
    };
  },
  onShow(){
    this.getRepRes();
  },
  onLoad(e) {
    console.log('personId===', uni.getStorageSync('personInfo').personId);
    console.log('onLoad=====', problemList)
    this.getRepRes();
    const type =this.type=e.type;
    console.log('open type=====', type)
      this.setNavBarName(type);

    try {
      this.reportType = uni.getStorageSync('reportType');
      let arr = uni.getStorageSync(type);
      if(arr && arr.length>0){
        this.problemList=arr;
      }else {
        this.problemList = JSON.parse(JSON.stringify(problemList[type]));
      }
      
    } catch (error) {
      console.log(error)
    }
    this.watchFinishNum();
  },
  methods: {
    watchFinishNum(){
      const retList = this.problemList.filter((itm) => {
        return itm.answer;
      });
      this.finishNum = retList.length;
      this.setMt();
    },

    seledMs(idx, opts) {
      console.log('currentIndex', this.currentIndex)
      if (!this.ck) {
        return;
      }
      this.ck = false;
      console.log("idx, opts", idx, opts);
      let problemList = this.problemList;
      problemList.map((item, index) => {
        if (index === idx) {
          item.answer = opts.opt;
          item.num = opts.num;
        }
        return item;
      });
      this.problemList = problemList;
      const retList = this.problemList.filter((itm) => {
        return itm.answer;
      });

      this.finishNum = retList.length;
      this.$nextTick(()=>{
        this.ck = true;
      })
      
      // if (this.finishNum === this.problemList.length) {
      //   this.postMs();
      //   return;
      // }
      if(this.currentIndex<this.problemList.length-1){
        this.currentIndex++;
      }
      this.setMt();
    },
    goPrevMs() {
      this.currentIndex--;
      this.setMt();
    },
    setErrTip(txt) {
      this.errTipTxt = txt
    },
    setMt() {
      const pType = this.problemList[this.currentIndex].pType;
      if (pType === "1") {
        this.mhqlTitle = "心理评估-失眠严重指数（ISI）";
        return;
      }
      if (pType === "2") {
        this.mhqlTitle = "心理评估-心理健康问卷";
        return;
      }
      this.mhqlTitle = "心理评估-焦虑问卷";
    },

    modifyConfirm(){
      let nameStr=`${this.type}Arr`;
      this[nameStr]=this.problemList;
      const problemList = [].concat(this.dataIsiArr, this.dataPhq9Arr, this.dataGad7Arr);
      console.log('problemList',problemList);
      if(!problemList.length){
        uni.showToast({
          title: `请填写后再提交`,
          duration: 3000,
          icon: "none",
        });
        return
      }
      // 焦虑答卷
      const dataGad7List = problemList.filter((item) => {
        return item.pType === "3";
      });
      let arrGad7 = [];
      let zScoreGad7 = 0;
      let zResultGad7 = "无焦虑";
      dataGad7List.forEach((item) => {
        zScoreGad7 += item.num;
        arrGad7.push({
          name: item.order,
          value: item.num.toString(),
        });
      });
      arrGad7 = arrGad7.length?JSON.stringify(arrGad7):null;
      switch (true) {
        case dataGad7List.length == 0:
          zResultGad7 = "未评估";
          break;
        case zScoreGad7 <= 4 && zScoreGad7 != 0:
          zResultGad7 = "无焦虑";
          break;
        case zScoreGad7 <= 9 && zScoreGad7 >= 5:
          zResultGad7 = "轻度焦虑";
          break;
        case zScoreGad7 <= 14 && zScoreGad7 >= 10:
          zResultGad7 = "中度焦虑";
          break;
        case zScoreGad7 >= 15:
          zResultGad7 = "重度焦虑";
          break;
      }
      console.log("dataGad7List", arrGad7, zScoreGad7, zResultGad7);

      // 失眠答卷
      const dataIsiList = problemList.filter((item) => {
        return item.pType === "1";
      });
      let arrIsi = [];
      let zScoreIsi = 0;
      let zResultIsi = "没有临床上显著的失眠症";
      dataIsiList.forEach((item) => {
        zScoreIsi += item.num;
        arrIsi.push({
          name: item.order,
          value: item.num.toString(),
        });
      });
      arrIsi = arrIsi.length ? JSON.stringify(arrIsi):null;
      switch (true) {
        case dataIsiList.length == 0:
          zResultIsi = "未评估";
          break;
        case zScoreIsi <= 7 && zScoreIsi !=0:
          zResultIsi = "没有临床上显著的失眠症";
          break;
        case zScoreIsi <= 14 && zScoreIsi >= 8:
          zResultIsi = "可能有阈下失眠症";
          break;
        case zScoreIsi <= 21 && zScoreIsi >= 15:
          zResultIsi = "可能有中度临床失眠症";
          break;
        case zScoreIsi >= 22:
          zResultIsi = "可能有重度临床失眠症";
          break;
      }
      console.log("dataIsiList", arrIsi, zScoreIsi, zResultIsi);

      // 心理健康答卷
      const dataPhq9List = problemList.filter((item) => {
        return item.pType === "2";
      });
      let arrPhq9 = [];
      let zScorePhq9 = 0;
      let zResultPhq9 = "无抑郁症";
      dataPhq9List.forEach((item) => {
        zScorePhq9 += item.num;
        arrPhq9.push({
          name: item.order,
          value: item.num.toString(),
        });
      });

      arrPhq9 = arrPhq9.length?JSON.stringify(arrPhq9):null;
      switch (true) {
        case dataPhq9List.length == 0:
          zResultPhq9 = "未评估";
          break;
        case zScorePhq9 <= 4 && zScorePhq9 != 0:
          zResultPhq9 = "无抑郁症";
          break;
        case zScorePhq9 <= 9 && zScorePhq9 >= 5:
          zResultPhq9 = "轻度抑郁症";
          break;
        case zScorePhq9 <= 14 && zScorePhq9 >= 10:
          zResultPhq9 = "可能有中度抑郁症";
          break;
        case zScorePhq9 <= 19 && zScorePhq9 >= 15:
          zResultPhq9 = "可能有中重度抑郁症";
          break;
        case zScorePhq9 >= 20:
          zResultPhq9 = "可能有重度抑郁症";
          break;
      }
      // console.log("dataPhq9List", arrPhq9, zScorePhq9, zResultPhq9);
      // console.log(uni.getStorageSync('personInfo').personId,9999)

      let healthInspectRes=uni.getStorageSync('healthInspectRes')||{};

      let tmppersonInfo=uni.getStorageSync('personInfo');
      let gender = typeof tmppersonInfo.gender == 'object'?'': tmppersonInfo.gender
      let params={
        ...healthInspectRes,
        personId: uni.getStorageSync('personInfo').personId,
        dataGad7: arrGad7,
        dataIsi: arrIsi,
        dataPhq9: arrPhq9,
        resultGad7: zResultGad7,
        resultIsi: zResultIsi,
        resultPhq9: zResultPhq9,
        scoreGad7: dataGad7List.length ? zScoreGad7 : null,
        scoreIsi: dataIsiList.length ? zScoreIsi : null,
        scorePhq9: dataPhq9List.length ? zScorePhq9 : null,
        assessmentTime: getNowTime(),
        name: tmppersonInfo.name,
        gender,
        age: tmppersonInfo.age,
        hotelName: tmppersonInfo.hotelName,
        houseId: tmppersonInfo.houseId,
      }
      this.scoreGad7 = zScoreGad7;
      this.resultGad7 = zResultGad7;
      this.scoreIsi = zScoreIsi;
      this.resultIsi = zResultIsi;
      this.scorePhq9 = zScorePhq9;
      this.resultPhq9 = zResultPhq9;

      this.ajaxGeli(params);

    },

    // 隔离人员
    ajaxGeli(params){
      console.log('====隔离人员提交======')
      console.log('提交入参====', params);

      getData('comprehensive', 'POST',  params).then(res=>{

        this.removeSoStorage();
        uni.redirectTo({
          url: `./qnarSucces?scoreGad7=${this.scoreGad7}&scoreIsi=${this.scoreIsi}&scorePhq9=${this.scorePhq9}&resultGad7=${this.resultGad7}&resultIsi=${this.resultIsi}&resultPhq9=${this.resultPhq9}`,
        });
      })
    },

    removeSoStorage(){
      this.$store.commit('REMOVE_DATA_IGP')
    },

    // // 群众调用
    // ajaxQunzhong(params){
    //   let dataFromUserBaseInfo=uni.getStorageSync('dataFromUserBaseInfo');

    //   let data ={
    //     ...params,
    //     ...dataFromUserBaseInfo,
    //   }

    //   console.log('========其他群众提交=======');
    //   console.log('提交入参====', data);

    //   getData('riskAss', 'POST',  data).then(res=>{
    //     try {
    //       uni.removeStorage({
    //         key: 'dataGad7'
    //       })
    //       uni.removeStorage({
    //         key: 'dataPhq9'
    //       })
    //       uni.removeStorage({
    //         key: 'dataIsi'
    //       })
    //     } catch (error) { }
        
    //     uni.redirectTo({
    //       url: `pages/healthInspect/qnarSucces?scoreGad7=${this.scoreGad7}&scoreIsi=${this.scoreIsi}&scorePhq9=${this.scorePhq9}&resultGad7=${this.resultGad7}&resultIsi=${this.resultIsi}&resultPhq9=${this.resultPhq9}`,
    //     });
    //   })
    // },

    postMs() {
      const problemList = this.problemList;
      console.log('存储====', this.type)
      console.log('存储====', problemList)
      uni.setStorage({
        key: this.type, 
        data: problemList
      })
      return ;

      // uni.redirectTo({
      //   url: `./success?type=${this.type}`,
      // });
      uni.reLaunch({
        url:'/packageIsolate/pages/isolateUser/index'
      })
      return ;


      // 焦虑答卷
      const dataGad7List = problemList.filter((item) => {
        return item.pType === "3";
      });
      let arrGad7 = [];
      let zScoreGad7 = 0;
      let zResultGad7 = "无焦虑";
      dataGad7List.forEach((item) => {
        zScoreGad7 += item.num;
        arrGad7.push({
          name: item.order,
          value: item.num.toString(),
        });
      });
      arrGad7 = JSON.stringify(arrGad7);
      switch (true) {
        case zScoreGad7 <= 4:
          zResultGad7 = "无焦虑";
          break;
        case zScoreGad7 <= 9 && zScoreGad7 >= 5:
          zResultGad7 = "轻度焦虑";
          break;
        case zScoreGad7 <= 14 && zScoreGad7 >= 10:
          zResultGad7 = "中度焦虑";
          break;
        case zScoreGad7 >= 15:
          zResultGad7 = "重度焦虑";
          break;
      }
      console.log("dataGad7List", arrGad7, zScoreGad7, zResultGad7);

      // 失眠答卷
      const dataIsiList = problemList.filter((item) => {
        return item.pType === "1";
      });
      let arrIsi = [];
      let zScoreIsi = 0;
      let zResultIsi = "没有临床上显著的失眠症";
      dataIsiList.forEach((item) => {
        zScoreIsi += item.num;
        arrIsi.push({
          name: item.order,
          value: item.num.toString(),
        });
      });
      arrIsi = JSON.stringify(arrIsi);
      switch (true) {
        case zScoreIsi <= 7:
          zResultIsi = "没有临床上显著的失眠症";
          break;
        case zScoreIsi <= 14 && zScoreIsi >= 8:
          zResultIsi = "可能有阈下失眠症";
          break;
        case zScoreIsi <= 21 && zScoreIsi >= 15:
          zResultIsi = "可能有中度临床失眠症";
          break;
        case zScoreIsi >= 22:
          zResultIsi = "可能有重度临床失眠症";
          break;
      }
      console.log("dataIsiList", arrIsi, zScoreIsi, zResultIsi);

      // 心理健康答卷
      const dataPhq9List = problemList.filter((item) => {
        return item.pType === "2";
      });
      let arrPhq9 = [];
      let zScorePhq9 = 0;
      let zResultPhq9 = "无抑郁症";
      dataPhq9List.forEach((item) => {
        zScorePhq9 += item.num;
        arrPhq9.push({
          name: item.order,
          value: item.num.toString(),
        });
      });
      arrPhq9 = JSON.stringify(arrPhq9);
      switch (true) {
        case zScorePhq9 <= 4:
          zResultPhq9 = "无抑郁症";
          break;
        case zScorePhq9 <= 9 && zScorePhq9 >= 5:
          zResultPhq9 = "轻度抑郁症";
          break;
        case zScorePhq9 <= 14 && zScorePhq9 >= 10:
          zResultPhq9 = "可能有中度抑郁症";
          break;
        case zScorePhq9 <= 19 && zScorePhq9 >= 15:
          zResultPhq9 = "可能有中重度抑郁症";
          break;
        case zScorePhq9 >= 20:
          zResultPhq9 = "可能有重度抑郁症";
          break;
      }
      console.log("dataPhq9List", arrPhq9, zScorePhq9, zResultPhq9);
      console.log(uni.getStorageSync('personInfo').personId,9999)
      mentalHealth({
        personId: uni.getStorageSync('personInfo').personId,
        dataGad7: arrGad7,
        dataIsi: arrIsi,
        dataPhq9: arrPhq9,
        resultGad7: zResultGad7,
        resultIsi: zResultIsi,
        resultPhq9: zResultPhq9,
        scoreGad7: zScoreGad7,
        scoreIsi: zScoreIsi,
        scorePhq9: zScorePhq9,
      }).then((res) => {
        console.log(mentalHealth, "res");
        uni.redirectTo({
          url: './success',
        });
      });
    },

    getRepRes(){
      try {
        let dataGad7 = uni.getStorageSync('dataGad7');    // 焦虑问卷：dataGad7
        let dataPhq9 = uni.getStorageSync('dataPhq9');  // 心理健康问卷：dataPhq9
        let dataIsi = uni.getStorageSync('dataIsi'); // 失眠严重指数：dataIsi
        // console.log('====', dataIsi, dataPhq9,  dataGad7)

        if(dataGad7){
          this.dataGad7Arr=dataGad7;
        }
        if(dataPhq9){
          this.dataPhq9Arr=dataPhq9;
        }
        if(dataIsi){
          this.dataIsiArr=dataIsi;
        }
        

      } catch (error) {
        console.log(error)
      }
    },

    setNavBarName(type){
      let nameMap={
        dataGad7: '焦虑问卷',
        dataPhq9: '心理健康问卷',
        dataIsi: '失眠严重指数',
      }
      uni.setNavigationBarTitle({
        title: `心理评估-${nameMap[type]}`
      })
    },

    orderClick (k) {
      this.currentIndex=k;
      this.setMt();
      uni.pageScrollTo({
          scrollTop: 0,
          duration: 300
      });
    },
  },
};
</script>

<style scoped lang="scss">
.mh-ql-wrapper {
  position: relative;
  padding-top: 30rpx;
  min-height: 100vh;
  // background-color: #f2f2f2;
  background-color: #F9F9F9;
  box-sizing: border-box;
  .mh-ql-err-tip {
    position: absolute;
    top: 30rpx;
    left: 0;
    right: 0;
    border-top: 1rpx solid #ffd9b4;
    border-bottom: 1rpx solid #ffd9b4;
    background-color: #fff9ed;
    display: flex;
    .mh-ql-err-tip-ic {
      flex: 0 0 84rpx;
      width: 84rpx;
      height: 80rpx;
      background-repeat: no-repeat;
      background-size: 40rpx 32rpx;
      background-position: center center;
      background-image: url(https://szgd-dev.tgovcloud.com/public/images/mentalHealth/tip.png);
    }
    .mh-ql-err-tip-txt {
      flex: 1;
      padding: 20rpx 0;
      font-size: 30rpx;
      font-family: PingFang SC;
      font-weight: 400;
      line-height: 40rpx;
      color: #ff6010;
      opacity: 1;
    }
    .mh-ql-err-tip-btn {
      flex: 0 0 84rpx;
      width: 84rpx;
      height: 80rpx;
      background-repeat: no-repeat;
      background-size: 30rpx 30rpx;
      background-position: center center;
      background-image: url(https://szgd-dev.tgovcloud.com/public/images/mentalHealth/del.png);
    }
  }
  .mh-ql-title {
    padding: 26rpx 32rpx;
    font-size: 32rpx;
    font-family: PingFang SC;
    font-weight: 400;
    line-height: 44rpx;
    border-bottom: 1px solid #f2f2f2;
    background-color: #fff;
  }
  .mh-ql-group {
    padding: 0 32rpx 1rpx 32rpx;
    background-color: #fff;
  }
  .mh-ql-question {
    padding: 30rpx 0;
    line-height: 42rpx;
    font-size: 30rpx;
    font-family: PingFang SC;
  }
  .mh-ql-answer-item {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;
    padding: 23rpx 28rpx 23rpx 30rpx;
    border-radius: 16rpx;
    background-color: #f2f2f2;
    .mh-ql-answer-txt {
      flex: 1;
      font-size: 30rpx;
      font-family: PingFang SC;
      font-weight: 500;
      line-height: 42rpx;
    }
    .mh-ql-answer-status {
      flex: 0 0 44rpx;
      width: 44rpx;
      height: 44rpx;
      border-radius: 50%;
      box-sizing: border-box;
      border: 1rpx solid #707070;
      background-color: #f0f0f0;
      &.selected {
        border: 1rpx solid #2c9af1;
        background-color: #2c9af1;
        background-image: url(https://szgd-dev.tgovcloud.com/public/images/mentalHealth/seled.png);
        background-position: center center;
        background-size: 24rpx 17rpx;
        background-repeat: no-repeat;
      }
    }
  }
  .mh-ql-answer-item-active {
    background: rgba(44, 154, 241, 0.1);
  }
  .mh-ql-count {
    padding: 30rpx 32rpx;
    font-size: 28rpx;
    font-family: PingFang SC;
    font-weight: 400;
    line-height: 40rpx;
  }
  .mh-ql-btn-wrapper {
    display: flex;
    // margin: 0 16rpx;
    padding: 20rpx 0;
    background-color: #fff;
    .mh-ql-btn {
      flex: 1;
      margin: 0 16rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 94rpx;
      border-radius: 16rpx;
      font-size: 34rpx;
      &.mh-ql-btn-next {
        border: 1rpx solid #2c9af1;
        background: #ffffff;
        color: #2c9af1;
      }
      &.mh-ql-btn-prev {
        border: 1rpx solid #2c9af1;
        background: #2c9af1;
        color: #ffffff;
      }
    }
    .btn-active {
      background-color: #2c9af1;
      color: #fff;
      &:active {
        background-color: #055c9e;
      }
    }
  }
  .sub-order {
    width: 90%;
    background-color: #fff;
    margin: 16rpx auto;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;
    .order-item {
      width: 25%;
      height: 60rpx;
      font-size: 24rpx;
      text-align: center;
      line-height: 60rpx;
      border-bottom: 1rpx solid #eaeaea;
      box-sizing: border-box;
      border-right: 1rpx solid #eaeaea;
    }
    .item-select {
      color: #fff;
      background-color: #13C563;
    }
  }
  .tongji {
    background-color: #fff;
    font-size: 32rpx;
    font-family: PingFang SC;
    font-weight: 400;
    color: #2C9AF1;
    .tj-head {
      border-bottom: 1rpx solid #F2F2F2;
      display: flex;
      height: 98rpx;
      padding: 0 32rpx;
      align-items: center;
      .tj-box {
        width: 46rpx;
        height: 46rpx;
        background: #2C9AF1;
        opacity: 1;
        border-radius: 3rpx;
        margin-right: 25rpx;
      }
      .th-item {
        display: flex;
      }
      .th-item-unwrite {
        margin-left: 64rpx;
        color: #000;
        .tj-box {
          background: #E2E2E2;
        }
      }
    }
    .tj-body {
      padding: 32rpx;
      display: flex;
      flex-wrap: wrap;
      .tj-order {
        width: 80rpx;
        height: 80rpx;
        background: #E2E2E2;
        opacity: 1;
        color: #000;
        border-radius: 3px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 30rpx;
        margin-bottom: 34rpx;
      }
      .item-select {
        background: #2C9AF1;
        color: #fff;
      }
    }
  }
}
</style>
